# coding=utf-8
__author__ = 'liubin'

import math
from flask import render_template
from flask import request
from flask.views import View
from flask.ext.login import login_required, current_user
from flask.ext.restful import Resource, marshal
from flask.ext.babelex import gettext as _
from sqlalchemy import or_, desc
from project import app, User, api_view, db
from project.common import tools
from project.forms import UserForm, PwdForm
from resource import user_resource_fields


class UserListApi(Resource):
    """
    REST:用户列表
    """
    method_decorators = [login_required]

    def get(self, **kwargs):
        """
        获得用户列表
        :param kwargs:
        :return:
        """
        size = request.args.get('size', None)
        start = request.args.get('start', None)
        qparam = request.args.get('query', None)
        order = request.args.get('order', None)
        dir = request.args.get('dir', None)
        draw = request.args.get('draw', '1')
        draw = int(draw)
        data = []
        query = User.query
        # 查询条件
        if qparam:
            query = query.filter(or_(User.name.like(u'%{}%'.format(qparam)), User.real_name.like(u'%{}%'.format(qparam))))
            #query = query.filter(or_(User.name.like(qparam), User.real_name.like(qparam)))
        # 排序
        if order and dir:
            if dir == 'desc':
                query = query.order_by(desc(getattr(User, order)))
            else:
                query = query.order_by(getattr(User, order))

        pager = tools.query_paging(query, size, start)
        # line = 1
        for user in pager['query']:
            rowid = 'row_' + str(user.id)
            data_user = {
                'DT_RowId': rowid,
                'DT_RowData': {
                    'pkey': user.id
                },
                'id': user.id,
                'name': user.name,
                'pwd': '*',
                'real_name': user.real_name
            }
            data.append(marshal(data_user, user_resource_fields))
            #line += 1
        #print(pager)
        return {'success': True, 'draw': draw, 'data': data, 'total': pager['total'], 'page': pager['page'],
                'start': pager['start']}

    def post(self, **kwargs):
        """
        追加用户
        :return:
        """
        form = UserForm(csrf_enabled=False)
        messages = []
        if form.validate_on_submit():
            exist_user = User.query.filter_by(name=form.name.data).first()
            if exist_user is None:
                user = User(name=form.name.data, pwd=form.pwd.data, real_name=form.real_name.data)
                db.session.add(user)
                db.session.commit()
                data_user = {
                    'id': user.id,
                    'name': user.name,
                    'pwd': '*',
                    'real_name': user.real_name
                }
                return {'success': True,  'data': marshal(data_user, user_resource_fields)}
            else:
                messages.append(u'该用户已经注册')
                return {'success': False,  'messages': messages}
        else:
            print('error')
            messages.extend(tools.get_form_error(form))
            return {'success': False,  'messages': messages}

api_view.add_resource(UserListApi, '/api/user', endpoint="api_user_list")

class UserApi(Resource):
    """
    REST: 单个用户
    """
    method_decorators = [login_required]

    def get(self, id, **kwargs):
        """
        获得单个用户
        :param id:
        :param kwargs:
        :return:
        """
        messages = []
        user =  User.query.filter_by(id=id).first()
        if user:
            data_user = {
                    'id': user.id,
                    'name': user.name,
                    'pwd': '*',
                    'real_name': user.real_name
                }
            return {'success': True,  'data': marshal(data_user, user_resource_fields)}
        else:
            messages.append(u'指定用户不存在')
            return {'success': False,  'messages': messages}

    def put(self, id, **kwargs):
        """
        更新单个用户
        :param id:
        :param kwargs:
        :return:
        """
        form = UserForm(csrf_enabled=False)
        messages = []
        if form.validate_on_submit():
            user = User.query.filter_by(id=id).first()
            if user:
                user.real_name = form.real_name.data
                db.session.commit()
                return {'success': True}
            else:
                messages.append(u'指定用户不存在')
                return {'success': False,  'messages': messages}
        else:
            # if form.pwd.data and form.pwd.data != '*':
            #     # 更新密码
            #     user = User.query.filter_by(id=id, pwd=form.pwd.data).first()
            #     if user:
            #         user.pwd = form.pwd.data
            #         db.session.commit()
            #         return {'success': True}
            #     else:
            #         messages.append('旧密码错误')
            #         return {'success': False,  'messages': messages}
            messages.extend(tools.get_form_error(form))
            return {'success': False,  'messages': messages}

    def delete(self, id, **kwargs):
        """
        删除用户
        :param id:
        :param kwargs:
        :return:
        """
        messages = []
        user =  User.query.filter_by(id=id).first()
        if user:
            if user.id != current_user.id:
                db.session.delete(user)
                db.session.commit()
                return {'success': True}
            else:
                messages.append(u'你不能删除你自己')
                return {'success': False,  'messages': messages}
        else:
            messages.append(u'该用户不存在')
            return {'success': False,  'messages': messages}

api_view.add_resource(UserApi, '/api/user/<int:id>', endpoint="api_user")


class UserPwdApi(Resource):
    """
    用户密码API
    """
    method_decorators = [login_required]

    def post(self, id, **kwargs):
        """
        更新密码
        :param id:
        :param kwargs:
        :return:
        """
        form = PwdForm(csrf_enabled=False)
        messages = []
        if form.validate_on_submit():
            user = User.query.filter_by(id=id).first()
            if user:
                if user.id != current_user.id:
                    user.pwd = form.pwd.data
                    db.session.commit()
                    return {'success': True}
                else:
                    messages.append(u'你不能在这里改你自己的密码')
                    return {'success': False,  'messages': messages}
            else:
                messages.append(u'指定用户不存在')
                return {'success': False,  'messages': messages}
        else:
            messages.extend(tools.get_form_error(form))
            return {'success': False,  'messages': messages}

api_view.add_resource(UserPwdApi, '/api/user/<int:id>/changePwd', endpoint="api_user_pwd")
